<template>
    <div class="chat-container theme-dark">
        <!-- 侧边栏：好友列表和功能区 -->
        <aside class="chat-sidebar">
            <!-- 搜索和添加好友 -->
            <div class="sidebar-header">
                <button class="back-btn" title="返回" @click="goBack">
                    <i class="fa fa-arrow-left"></i>
                </button>
                <div class="search-box">
                    <i class="fa fa-search"></i>
                    <input type="text" placeholder="搜索好友..." v-model="searchQuery" @input="filterFriends">
                </div>
                <button class="add-friend-btn" @click="showAddFriendModal = true">
                    <i class="fa fa-plus"></i>
                </button>
            </div>

            <!-- 好友请求提示 -->
            <div v-if="friendRequests.length > 0" class="friend-requests-notification"
                @click="showFriendRequests = true">
                <i class="fa fa-bell"></i>
                <span>你有 {{ friendRequests.length }} 个好友请求</span>
                <div class="notification-badge">{{ friendRequests.length }}</div>
            </div>

            <!-- 好友列表 -->
            <div class="friends-list">
                <div class="list-section">
                    <h3 class="section-title">在线好友</h3>
                    <div class="friend-item" v-for="friend in onlineFriends" :key="friend.id"
                        :class="{ 'active': selectedFriendId === friend.id }" @click="selectFriend(friend)"
                        @contextmenu.prevent="showProfileCard(friend, $event)">
                        <div class="friend-avatar">
                            <img :src="friend.avatar" alt="好友头像" @error="handleAvatarError">
                            <span class="online-indicator"></span>
                        </div>
                        <div class="friend-info">
                            <div class="friend-name">{{ friend.nickname }}</div>
                            <div class="last-message" :class="{ 'unread': friend.unreadCount > 0 }">
                                {{ friend.lastMessage || '点击开始聊天' }}
                            </div>
                        </div>
                        <div class="friend-meta">
                            <div class="message-time">{{ formatTime(friend.lastActiveTime) }}</div>
                            <div v-if="friend.unreadCount > 0" class="unread-badge">
                                {{ friend.unreadCount }}
                            </div>
                        </div>
                    </div>
                </div>

                <div class="list-section">
                    <h3 class="section-title">离线好友</h3>
                    <div class="friend-item" v-for="friend in offlineFriends" :key="friend.id"
                        :class="{ 'active': selectedFriendId === friend.id }" @click="selectFriend(friend)"
                        @contextmenu.prevent="showProfileCard(friend, $event)">
                        <div class="friend-avatar">
                            <img :src="friend.avatar" alt="好友头像" @error="handleAvatarError">
                            <span class="offline-indicator"></span>
                        </div>
                        <div class="friend-info">
                            <div class="friend-name">{{ friend.nickname }}</div>
                            <div class="last-message">
                                {{ friend.lastMessage || '点击开始聊天' }}
                            </div>
                        </div>
                        <div class="friend-meta">
                            <div class="message-time">{{ formatTime(friend.lastActiveTime) }}</div>
                            <div v-if="friend.unreadCount > 0" class="unread-badge">
                                {{ friend.unreadCount }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </aside>

        <!-- 主聊天区域 -->
        <main class="chat-main" v-if="selectedFriend">
            <!-- 聊天头部：好友信息和操作 -->
            <div class="chat-header">
                <div class="friend-info" @click="showProfileCard(selectedFriend)">
                    <div class="friend-avatar">
                        <img :src="selectedFriend.avatar" alt="好友头像" @error="handleAvatarError">
                        <span class="online-indicator" v-if="selectedFriend.online"></span>
                        <span class="offline-indicator" v-else></span>
                    </div>
                    <div>
                        <div class="friend-name">{{ selectedFriend.nickname }}</div>
                        <div class="friend-status">
                            {{ selectedFriend.online ? '在线' : `最后在线: ${formatTime(selectedFriend.lastActiveTime)}` }}
                        </div>
                    </div>
                </div>
                <div class="chat-actions">
                    <button class="action-btn" title="查看资料" @click="showProfileCard(selectedFriend)">
                        <i class="fa fa-user-o"></i>
                    </button>
                    <button class="action-btn" title="更多选项">
                        <i class="fa fa-ellipsis-v"></i>
                    </button>
                </div>
            </div>

            <!-- 聊天消息区域 -->
            <div class="chat-messages" ref="messageContainer">
                <div class="loading-history" v-if="isLoadingHistory">
                    <i class="fa fa-spinner fa-spin"></i> 加载更多历史消息...
                </div>
                <!-- 日期分隔线 -->
                <div class="date-divider" v-if="messages.length > 0">
                    {{ getMessageDate() }}
                </div>

                <!-- 消息列表 -->
                <div class="message" v-for="(msg, index) in messages" :key="index"
                    :class="{ 'sent': msg.sentByMe, 'received': !msg.sentByMe }">
                    <div class="message-bubble">
                        {{ msg.content }}
                    </div>
                    <div class="message-time">
                        {{ formatMessageTime(msg.timestamp) }}
                        <i class="fa fa-check-circle" v-if="msg.read && msg.sentByMe"></i>
                        <i class="fa fa-check" v-if="!msg.read && msg.sentByMe"></i>
                    </div>
                </div>

                <!-- 正在输入提示 -->
                <div class="typing-indicator" v-if="isFriendTyping">
                    <div class="dot"></div>
                    <div class="dot"></div>
                    <div class="dot"></div>
                </div>
            </div>

            <!-- 消息输入区域 -->
            <div class="message-input-area">
                <div class="input-tools">
                    <button class="tool-btn" title="表情">
                        <i class="fa fa-smile-o"></i>
                    </button>
                    <button class="tool-btn" title="图片">
                        <i class="fa fa-picture-o"></i>
                    </button>
                    <button class="tool-btn" title="文件">
                        <i class="fa fa-paperclip"></i>
                    </button>
                </div>
                <textarea v-model="newMessage" class="message-input" placeholder="输入消息..."
                    @keydown.enter.exact="sendMessage" @keydown.enter.shift="newMessage += '\n'"
                    @input="handleTyping"></textarea>
                <button class="send-btn" @click="sendMessage" :disabled="!newMessage.trim()">
                    <i class="fa fa-paper-plane"></i>
                </button>
            </div>
        </main>

        <!-- 未选择好友时的提示 -->
        <div class="no-selection" v-else>
            <div class="no-selection-content">
                <i class="fa fa-comments-o"></i>
                <h3>选择一个好友开始聊天</h3>
                <p>点击好友列表中的联系人开始对话</p>
            </div>
        </div>

        <!-- 好友资料卡片 -->
        <div class="profile-card" v-if="showProfile" :style="{ top: profileTop + 'px', left: profileLeft + 'px' }"
            @click.stop>
            <div class="profile-header">
                <img :src="profileUser.avatar" alt="用户头像" class="profile-avatar" @error="handleAvatarError">
                <div class="profile-name-status">
                    <div class="profile-name">{{ profileUser.nickname }}</div>
                    <div class="profile-status">
                        <span class="status-dot" :class="{
                            'online': profileUser.onlineStatus === 1,
                            'busy': profileUser.onlineStatus === 2,
                            'away': profileUser.onlineStatus === 3,
                            'offline': profileUser.onlineStatus === 0
                        }"></span>
                        {{
                            profileUser.onlineStatus === 1 ? '在线' :
                                profileUser.onlineStatus === 2 ? '忙碌' :
                                    profileUser.onlineStatus === 3 ? '离开' : '离线'
                        }}
                    </div>
                </div>
                <button class="close-profile" @click="showProfile = false">
                    <i class="fa fa-times"></i>
                </button>
            </div>

            <div class="profile-body">
                <div class="profile-info-item">
                    <label>用户名</label>
                    <span>{{ profileUser.username }}</span>
                </div>
                <div class="profile-info-item">
                    <label>地区</label>
                    <span>{{ profileUser.location || '未设置' }}</span>
                </div>
                <div class="profile-info-item">
                    <label>个性签名</label>
                    <span>{{ profileUser.bio || '暂无签名' }}</span>
                </div>
                <div class="profile-info-item">
                    <label>加入时间</label>
                    <span>{{ formatJoinTime(profileUser.joinTime) }}</span>
                </div>
            </div>

            <div class="profile-actions">
                <button class="message-btn" @click="startChatWithProfileUser">
                    <i class="fa fa-comment-o mr-1"></i> 发消息
                </button>
                <button class="more-btn">
                    <i class="fa fa-ellipsis-h"></i>
                </button>
            </div>
        </div>

        <!-- 点击空白处关闭资料卡片 -->
        <div class="profile-backdrop" v-if="showProfile" @click="showProfile = false"></div>

        <!-- 添加好友弹窗 -->
        <div class="modal-overlay" v-if="showAddFriendModal" @click="showAddFriendModal = false">
            <div class="modal" @click.stop>
                <div class="modal-header">
                    <h3>添加好友</h3>
                    <button class="close-btn" @click="showAddFriendModal = false">
                        <i class="fa fa-times"></i>
                    </button>
                </div>

                <div class="modal-body">
                    <input type="text" class="search-input" placeholder="输入手机号搜索" v-model="addFriendQuery">
                    <button class="search-btn" @click="searchUsers" :disabled="!addFriendQuery.trim()">
                        搜索
                    </button>

                    <div class="search-result" v-if="searchedUser">
                        <h4>搜索结果</h4>
                        <div class="user-item">
                            <img :src="searchedUser.avatar" alt="用户头像" class="user-avatar" @error="handleAvatarError">
                            <div class="user-info">
                                <div class="user-name">{{ searchedUser.nickname }}</div>
                                <div class="user-username">{{ searchedUser.username }}</div>
                                <div class="user-signature">{{ searchedUser.signature || '暂无签名' }}</div>
                            </div>
                            <button class="add-btn" @click="() => openVerifyModal(searchedUser.id)" :disabled="!searchedUser || !searchedUser.id || searchedUser.isFriend ||
                                searchedUser.isRequestSent">
                                {{ searchedUser.isFriend ? '已添加' : searchedUser.isRequestSent ? '请求已发送' : '添加好友' }}
                            </button>
                        </div>
                    </div>

                    <div class="no-result" v-if="searchCompleted && !searchedUser">
                        未找到该用户，请检查手机号是否正确
                    </div>
                </div>
            </div>
        </div>

        <!-- 验证消息弹窗 -->
        <div class="modal-overlay" v-if="showVerifyMessageModal" @click="showVerifyMessageModal = false">
            <div class="modal" @click.stop>
                <div class="modal-header">
                    <h3>输入验证消息</h3>
                    <button class="close-btn" @click="showVerifyMessageModal = false">
                        <i class="fa fa-times"></i>
                    </button>
                </div>
                <div class="modal-body">
                    <textarea class="verify-message-input" placeholder="请输入验证消息（如：我是XX，想加你交流）"
                        v-model="verifyMessageForModal" rows="3"></textarea>
                </div>
                <div class="modal-footer">
                    <button class="cancel-btn" @click="showVerifyMessageModal = false">取消</button>
                    <button class="confirm-btn" @click="confirmSendFriendRequest">确认发送</button>
                </div>
            </div>
        </div>

        <!-- 好友请求弹窗 -->
        <div class="modal-overlay" v-if="showFriendRequests" @click="showFriendRequests = false">
            <div class="modal" @click.stop>
                <div class="modal-header">
                    <h3>好友请求</h3>
                    <button class="close-btn" @click="showFriendRequests = false">
                        <i class="fa fa-times"></i>
                    </button>
                </div>
                <div class="modal-body">
                    <div v-if="friendRequests.length === 0" class="no-requests">
                        暂无好友请求
                    </div>

                    <div class="request-item" v-for="request in friendRequests" :key="request.id">
                        <img :src="request.avatar" alt="用户头像" class="request-avatar" @error="handleAvatarError">
                        <div class="request-info">
                            <div class="request-name">{{ request.nickname }}</div>
                            <div class="request-username">{{ request.username }}</div>
                            <div class="request-time">{{ formatTime(request.timestamp) }}</div>
                        </div>
                        <div class="request-actions">
                            <button class="accept-btn" @click="acceptFriendRequest(request.id)">
                                <i class="fa fa-check"></i> 接受
                            </button>
                            <button class="reject-btn" @click="rejectFriendRequest(request.id)">
                                <i class="fa fa-times"></i> 拒绝
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import request from '@/utils/request';
import { ElMessage } from 'element-plus';

const router = useRouter();

const searchQuery = ref('');
const newMessage = ref('');
const selectedFriendId = ref(null);
const showAddFriendModal = ref(false);
const addFriendQuery = ref('');
const isFriendTyping = ref(false);
const typingTimeout = ref(null);
const showProfile = ref(false);
const profileUser = ref(null);
const profileTop = ref(0);
const profileLeft = ref(0);
const showFriendRequests = ref(false);

const searchedUser = ref(null);
const searchCompleted = ref(false);
const showVerifyMessageModal = ref(false);
const verifyMessageForModal = ref('');

const historyPage = ref(1);
const historySize = ref(20);
const hasMoreHistory = ref(true);
const isLoadingHistory = ref(false);

let ws = null;
let heartBeatTimer = null;

const currentUser = ref(JSON.parse(localStorage.getItem('currentUser')));

const friends = ref([]);
const friendRequests = ref([]);

const filteredFriends = computed(() => {
    if (!searchQuery.value) return friends.value;
    const query = searchQuery.value.toLowerCase();
    return friends.value.filter(friend =>
        friend.nickname.toLowerCase().includes(query) ||
        friend.username.toLowerCase().includes(query)
    );
});

const onlineFriends = computed(() =>
    filteredFriends.value.filter(friend => friend.onlineStatus === 1)
);
const offlineFriends = computed(() =>
    filteredFriends.value.filter(friend => friend.onlineStatus !== 1)
);

const selectedFriend = computed(() => {
  if (!selectedFriendId.value) return null;
  // 关键：把选中的好友ID和friends数组中的ID都转成字符串
  const targetId = String(selectedFriendId.value);
  return friends.value.find(friend => String(friend.id) === targetId) || null;
});

const messages = ref([]);

// ======================
// WebSocket 核心逻辑
// ======================

const initWebSocket = () => {
    const userToken = localStorage.getItem('userToken');
    if (!userToken) {
        ElMessage.error('缺少 Token，请先登录');
        return;
    }

    // 如果已有连接，先关闭
    if (ws) {
        ws.close();
    }

    const userId = currentUser.value?.userId;

    // 只需要 userId，不需要 friendId
    if (!userId) {
        console.warn('缺少 userId，无法初始化 WebSocket');
        return;
    }

    const baseUrl = import.meta.env.VITE_API_BASE_URL;
    const cleanedBaseUrl = baseUrl.replace(/\/$/, '');
    const host = cleanedBaseUrl.replace(/^https?:\/\//, '');
    const wsProtocol = baseUrl.startsWith('https') ? 'wss://' : 'ws://';

    // 移除 friendId 参数，只使用 userId
    const wsUrl = `${wsProtocol}${host}/ws/chat?userId=${currentUser.value.userId}&token=${userToken}`;

    console.log("WebSocket URL：", wsUrl);
    ws = new WebSocket(wsUrl);

    ws.onopen = () => {
        console.log('WebSocket 连接已建立');
        ElMessage.success('聊天服务已连接');
        startHeartbeat();
    };

    ws.onmessage = (event) => {
        try {
            const receivedMsg = JSON.parse(event.data);
            const userId = currentUser.value?.userId;
            const friendId = selectedFriendId.value;

            console.log('【接收原始消息】', receivedMsg); // 新增：跟踪所有消息

            // 首先处理心跳消息，避免后续逻辑出错
            if (receivedMsg.type === 'ping' || receivedMsg.type === 'pong') {
                console.log('收到心跳消息：', receivedMsg.type);
                return;
            }

            // 处理已读确认消息
            if (receivedMsg.type === 'read_ack') {
                const msgIndex = messages.value.findIndex(msg => msg.id === receivedMsg.messageId);
                if (msgIndex !== -1) {
                    messages.value[msgIndex].read = true;
                    console.log('【已读确认】消息ID：', receivedMsg.messageId);
                }
                return;
            }

            // 处理错误消息
            if (receivedMsg.type === 'error') {
                console.error('WebSocket 错误:', receivedMsg.content);
                ElMessage.error(receivedMsg.content || '消息处理错误'); // 新增：用户可见的错误提示
                return;
            }

            // 处理普通消息
            if (receivedMsg.type === 'message') {
                console.log('【收到业务消息】', receivedMsg);

                // 验证必要字段
                if (!receivedMsg.senderId || !receivedMsg.receiverId) {
                    console.warn('消息缺少必要字段:', receivedMsg);
                    return;
                }

                // 1. 统一ID类型为字符串（解决数字/字符串不匹配问题）
                const senderId = String(receivedMsg.senderId);
                const receiverId = String(receivedMsg.receiverId);
                const currentUserId = String(userId || '');
                const currentFriendId = String(friendId || '');

                // 2. 统一时间字段（解决自己发送的消息时间不对的问题）
                // 优先使用timestamp，若没有则尝试转换sentAt，最后用当前时间兜底
                let messageTimestamp;
                if (receivedMsg.timestamp) {
                    messageTimestamp = Number(receivedMsg.timestamp); // 确保是数字类型
                } else if (receivedMsg.sentAt) {
                    // 处理后端可能返回的ISO时间字符串（如"2025-10-02T10:33:50.583Z"）
                    messageTimestamp = new Date(receivedMsg.sentAt).getTime();
                } else {
                    messageTimestamp = Date.now(); // 兜底：用当前时间
                }
                console.log('【时间字段处理】', {
                    originalTimestamp: receivedMsg.timestamp,
                    originalSentAt: receivedMsg.sentAt,
                    convertedTimestamp: messageTimestamp
                });

                // 3. 格式化消息对象
                const formattedMsg = {
                    id: receivedMsg.id || `${Date.now()}-${senderId}`, // 更唯一的ID生成方式
                    content: receivedMsg.content || '',
                    timestamp: messageTimestamp, // 使用统一处理后的时间戳
                    sentByMe: senderId === currentUserId,
                    read: !!receivedMsg.read, // 确保是布尔值
                    senderId: senderId,
                    receiverId: receiverId
                };

                // 4. 判断是否为当前聊天消息
                const isCurrentChat = (
                    (senderId === currentFriendId && receiverId === currentUserId) ||
                    (senderId === currentUserId && receiverId === currentFriendId)
                );
                console.log('【当前聊天判断】', {
                    senderId, receiverId, currentUserId, currentFriendId, isCurrentChat
                });

                if (isCurrentChat) {
                    messages.value = [...messages.value, formattedMsg];
                    console.log('【消息已添加到当前聊天】', formattedMsg);
                    scrollToBottom();

                    // 收到的消息需要发送已读确认
                    if (!formattedMsg.sentByMe) {
                        ws.send(JSON.stringify({
                            type: 'read_ack',
                            messageId: formattedMsg.id,
                            senderId: currentUserId,
                            receiverId: senderId
                        }));
                    }
                } else {
                    // 非当前聊天消息，更新未读数
                    updateFriendUnreadCount(senderId);
                    console.log('【非当前聊天消息，已更新未读数】', senderId);
                }

                // 更新好友列表的最后消息
                updateFriendLastMessage({
                    ...receivedMsg,
                    senderId: senderId,
                    receiverId: receiverId,
                    timestamp: messageTimestamp // 用统一后的时间戳
                });
            }
        } catch (error) {
            console.error('解析消息失败:', error);
            console.error('原始消息数据:', event.data);
            ElMessage.error('消息解析失败，请重试'); // 新增：用户可见的错误提示
        }
    };

    ws.onclose = (event) => {
        console.log('WebSocket 连接关闭，代码:', event.code);
        ElMessage.warning('聊天连接已断开，3秒后尝试重连...');
        stopHeartbeat();
        setTimeout(() => {
            // 无论是否选择了好友都尝试重连
            initWebSocket();
        }, 3000);
    };

    ws.onerror = (error) => {
        console.error('WebSocket 错误:', error);
        ElMessage.error('聊天连接异常，请检查网络');
        stopHeartbeat();
    };
};

const updateFriendLastMessage = (message) => {
    // 确保消息对象和必要字段存在
    if (!message || !message.senderId) {
        return;
    }

    const userId = currentUser.value?.userId;
    const friendId = message.senderId === userId ? message.receiverId : message.senderId;

    // 确保 friendId 存在
    if (!friendId) {
        return;
    }

    const friendIndex = friends.value.findIndex(f => f.id === friendId);
    if (friendIndex !== -1) {
        friends.value[friendIndex].lastMessage = message.content;
        friends.value[friendIndex].lastActiveTime = message.sentAt;
    }
};

const startHeartbeat = () => {
    stopHeartbeat();
    heartBeatTimer = setInterval(() => {
        if (ws && ws.readyState === WebSocket.OPEN) {
            ws.send(JSON.stringify({ type: 'ping' }));
        }
    }, 30000);
};

const stopHeartbeat = () => {
    if (heartBeatTimer) {
        clearInterval(heartBeatTimer);
        heartBeatTimer = null;
    }
};

const updateFriendUnreadCount = (senderId) => {
    // 确保 senderId 存在
    if (!senderId) {
        return;
    }

    const friendIndex = friends.value.findIndex(f => f.id === senderId);
    if (friendIndex !== -1) {
        const currentUnread = friends.value[friendIndex].unreadCount || 0;
        friends.value[friendIndex].unreadCount = currentUnread + 1;

        // 更新最后活动时间
        friends.value[friendIndex].lastActiveTime = new Date().toISOString();
    }
};

// ======================
// 消息发送
// ======================

const sendMessage = () => {
    const content = newMessage.value.trim();
    if (!content) return;

    if (!ws || ws.readyState !== WebSocket.OPEN) {
        ElMessage.error('消息发送失败：连接未就绪');
        return;
    }

    const userId = currentUser.value?.userId;
    const friendId = selectedFriendId.value;

    if (!userId || !friendId) {
        ElMessage.error('用户信息异常');
        return;
    }

    const message = {
        type: 'message',
        senderId: userId,
        receiverId: friendId,
        content: content,
        messageType: 0,
        timestamp: new Date().getTime()
    };

    ws.send(JSON.stringify(message));

    messages.value.push({
        ...message,
        sentByMe: true,
        read: false
    });

    // 更新好友列表中的最后消息
    updateFriendLastMessage(message);

    newMessage.value = '';
    scrollToBottom();
};
// ======================
// 好友选择
// ======================

const selectFriend = (friend) => {
    selectedFriendId.value = friend.id;

    if (friend.unreadCount > 0) {
        const index = friends.value.findIndex(f => f.id === friend.id);
        if (index !== -1) {
            friends.value[index].unreadCount = 0;
            markAllAsRead(friend.id);
        }
    }

    messages.value = [];
    historyPage.value = 1;
    hasMoreHistory.value = true;
    fetchHistoryMessages(friend.id, true);
    // 移除 initWebSocket() 调用，因为连接已经在组件挂载时建立了
};

// ======================
// 其他业务逻辑
// ======================

const markAllAsRead = async (friendId) => {
    try {
        await request.post('/chat/mark-all-read', {
            currentUserId: currentUser.value.userId,
            friendId: friendId
        });
    } catch (error) {
        console.error('标记已读失败:', error);
    }
};

const fetchHistoryMessages = async (friendId, isRefresh = false) => {
    if (!friendId || !currentUser.value?.userId) {
        console.error('缺少必要参数');
        return;
    }

    if (isRefresh) {
        historyPage.value = 1;
        hasMoreHistory.value = true;
        messages.value = [];
    }

    if (!hasMoreHistory.value) return;

    try {
        isLoadingHistory.value = true;
        const response = await request.get('/chat/history', {
            params: {
                currentUserId: currentUser.value.userId,
                friendId: friendId,
                page: historyPage.value,
                size: historySize.value
            }
        });

        const { records, pages } = response.data;
        hasMoreHistory.value = historyPage.value < pages;

        const formattedMessages = records.map(msg => {
            // 统一将sentAt（ISO字符串）转换为数字时间戳
            let numericTimestamp;
            if (msg.sentAt) {
                numericTimestamp = new Date(msg.sentAt).getTime(); // ISO字符串转数字时间戳
            } else if (msg.timestamp) {
                numericTimestamp = Number(msg.timestamp); // 若后端有timestamp字段，直接用
            } else {
                numericTimestamp = Date.now(); // 兜底
            }

            return {
                id: msg.id,
                content: msg.content,
                timestamp: numericTimestamp, // 统一为数字时间戳
                sentByMe: msg.senderId === currentUser.value.userId,
                read: msg.isRead
            };
        });

        if (isRefresh) {
            messages.value = formattedMessages;
        } else {
            messages.value.unshift(...formattedMessages);
        }

        historyPage.value++;

        if (isRefresh) {
            setTimeout(scrollToBottom, 100);
        }
    } catch (error) {
        console.error('获取历史消息失败:', error);
        ElMessage.error('加载历史消息失败');
    } finally {
        isLoadingHistory.value = false;
    }
};

const goBack = () => {
    router.go(-1);
};

const searchUsers = () => {
    const phone = addFriendQuery.value.trim();
    if (!phone) {
        ElMessage.warning('请输入要搜索的手机号');
        return;
    }
    if (!/^1\d{10}$/.test(phone)) {
        ElMessage.warning('请输入正确的11位手机号');
        return;
    }

    searchedUser.value = null;
    searchCompleted.value = false;

    request.get('/chat/search-by-phone', {
        params: { phone: phone }
    })
        .then(response => {
            searchCompleted.value = true;
            const user = response.data;
            if (user && user.id) {
                searchedUser.value = {
                    id: user.id,
                    nickname: user.nickname || user.username || '未知用户',
                    username: user.username || 'unknown',
                    avatar: user.avatar
                        ? (user.avatar.includes('http') ? user.avatar : `${import.meta.env.VITE_API_BASE_URL}/${user.avatar}`)
                        : 'https://picsum.photos/id/64/200',
                    bio: user.bio || '暂无个性签名',
                    isFriend: friends.value.some(friend => friend.id === user.id),
                    isRequestSent: friendRequests.value.some(req =>
                        req.fromUser?.id === currentUser.value.id &&
                        req.toUser?.id === user.id &&
                        req.status === 0
                    )
                };
                ElMessage.success(`找到用户：${searchedUser.value.nickname}`);
            } else {
                searchedUser.value = null;
                ElMessage.info('未找到匹配的用户');
            }
        })
        .catch(error => {
            console.error('按手机号搜索用户失败:', error);
            ElMessage.error('搜索失败，请稍后重试');
            searchCompleted.value = true;
            searchedUser.value = null;
        });
};

let currentUserId = null;

const openVerifyModal = (userId) => {
    if (!userId || (typeof userId !== 'number' && typeof userId !== 'string')) {
        ElMessage.error('用户信息异常，无法添加');
        console.error('无效的用户 ID:', userId);
        return;
    }
    currentUserId = userId;
    showVerifyMessageModal.value = true;
};

const confirmSendFriendRequest = () => {
    if (currentUserId === null) {
        ElMessage.error('未找到目标用户');
        showVerifyMessageModal.value = false;
        return;
    }

    if (!searchedUser.value || searchedUser.value.id !== currentUserId) {
        ElMessage.error('用户信息已失效，请重新搜索');
        showVerifyMessageModal.value = false;
        currentUserId = null;
        return;
    }

    const message = verifyMessageForModal.value.trim() || '想加你为好友，一起交流吧~';

    request.post('/chat/friend-requests/send', {
        toUserId: currentUserId,
        message: message
    })
        .then(response => {
            ElMessage.success(`已向${searchedUser.value.nickname}发送好友请求`);
            searchedUser.value.isRequestSent = true;
            showVerifyMessageModal.value = false;
            verifyMessageForModal.value = '';
            currentUserId = null;
        })
        .catch(error => {
            console.error('发送请求失败:', error);
            ElMessage.error('发送请求失败，请稍后重试');
            currentUserId = null;
        });
};

const showProfileCard = (friend, event) => {
    profileUser.value = { ...friend };
    showProfile.value = true;

    if (event) {
        profileTop.value = event.clientY;
        profileLeft.value = event.clientX;
    } else {
        const container = document.querySelector('.chat-container');
        if (container) {
            const rect = container.getBoundingClientRect();
            profileTop.value = rect.top + rect.height / 2 - 150;
            profileLeft.value = rect.left + rect.width / 2 - 175;
        }
    }

    adjustProfilePosition();
};

const adjustProfilePosition = () => {
    const profile = document.querySelector('.profile-card');
    if (!profile) return;

    const profileRect = profile.getBoundingClientRect();
    const viewportWidth = window.innerWidth;
    const viewportHeight = window.innerHeight;

    if (profileRect.right > viewportWidth) {
        profileLeft.value = Math.max(0, viewportWidth - profileRect.width - 20);
    }

    if (profileRect.bottom > viewportHeight) {
        profileTop.value = Math.max(0, viewportHeight - profileRect.height - 20);
    }
};

const startChatWithProfileUser = () => {
    if (profileUser.value) {
        selectFriend(profileUser.value);
        showProfile.value = false;
    }
};

const formatTime = (timestamp) => {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    const now = new Date();
    const diffInSeconds = Math.floor((now - date) / 1000);

    if (date.toDateString() === now.toDateString()) {
        return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    }

    const yesterday = new Date(now);
    yesterday.setDate(now.getDate() - 1);
    if (date.toDateString() === yesterday.toDateString()) {
        return '昨天';
    }

    if (date.getFullYear() === now.getFullYear()) {
        return `${date.getMonth() + 1}月${date.getDate()}日`;
    }

    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
};

const formatMessageTime = (timestamp) => {
    try {
        // 先将timestamp转为数字（处理字符串类型的时间戳）
        const numericTimestamp = Number(timestamp);
        // 验证时间戳有效性（数字且大于0）
        if (isNaN(numericTimestamp) || numericTimestamp <= 0) {
            console.warn('无效时间戳:', timestamp);
            return '--:--';
        }
        const date = new Date(numericTimestamp);
        // 验证日期对象是否有效
        if (isNaN(date.getTime())) {
            console.warn('时间戳转换失败:', timestamp);
            return '--:--';
        }
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        return `${hours}:${minutes}`;
    } catch (error) {
        console.error('时间格式化出错:', error, '时间戳:', timestamp);
        return '--:--';
    }
};

const getMessageDate = () => {
    try {
        if (messages.value.length === 0) return '';

        const lastMsg = messages.value[messages.value.length - 1];
        // 验证最后一条消息的时间戳
        const numericTimestamp = Number(lastMsg.timestamp);
        if (isNaN(numericTimestamp) || numericTimestamp <= 0) {
            console.warn('最后一条消息时间戳无效:', lastMsg.timestamp);
            return '日期异常';
        }

        const latestDate = new Date(numericTimestamp);
        if (isNaN(latestDate.getTime())) {
            console.warn('最后一条消息时间转换失败:', lastMsg.timestamp);
            return '日期异常';
        }

        const now = new Date();
        if (latestDate.toDateString() === now.toDateString()) {
            return '今天';
        }

        const yesterday = new Date(now);
        yesterday.setDate(now.getDate() - 1);
        if (latestDate.toDateString() === yesterday.toDateString()) {
            return '昨天';
        }

        return `${latestDate.getFullYear()}年${latestDate.getMonth() + 1}月${latestDate.getDate()}日`;
    } catch (error) {
        console.error('日期分隔线格式化出错:', error);
        return '日期异常';
    }
};

const formatJoinTime = (timestamp) => {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
};

const messageContainer = ref(null);
const scrollToBottom = () => {
    if (messageContainer.value) {
        messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
    }
};

const handleAvatarError = (e) => {
    e.target.src = 'https://picsum.photos/id/64/200';
};

const handleResize = () => {
    if (showProfile.value) {
        adjustProfilePosition();
    }
};

const handleTyping = () => {
    if (!selectedFriend.value || !selectedFriend.value.online) return;
    if (typingTimeout.value) {
        clearTimeout(typingTimeout.value);
    }
    if (newMessage.value.trim()) {
        isFriendTyping.value = true;
        typingTimeout.value = setTimeout(() => {
            isFriendTyping.value = false;
        }, 3000);
    } else {
        isFriendTyping.value = false;
    }
};

const acceptFriendRequest = (requestId) => {
    request.post('/chat/friend-requests/accept', requestId)
        .then(response => {
            fetchFriendRequests();
            fetchFriends();
            ElMessage.success('已成功添加为好友');
        })
        .catch(error => {
            console.error('接受好友请求失败:', error);
            ElMessage.error('操作失败，请重试');
        });
};

const rejectFriendRequest = (requestId) => {
    request.post('/chat/friend-requests/reject', requestId)
        .then(response => {
            fetchFriendRequests();
            ElMessage.success('已拒绝该好友请求');
        })
        .catch(error => {
            console.error('拒绝好友请求失败:', error);
            ElMessage.error('操作失败，请重试');
        });
};

const fetchFriendRequests = () => {
    request.get('/chat/friend-requests')
        .then(response => {
            friendRequests.value = response.data;
        })
        .catch(error => {
            console.error('刷新好友请求列表失败:', error);
        });
};

const fetchFriends = () => {
    request.get('/chat/friends')
        .then(response => {
            friends.value = response.data;
        })
        .catch(error => {
            console.error('刷新好友列表失败:', error);
        });
};

// ======================
// 生命周期
// ======================

onMounted(() => {
    const user = JSON.parse(localStorage.getItem('currentUser'));
    if (!user?.userId) {
        ElMessage.error('请先登录');
        router.push('/login');
        return;
    }
    currentUser.value = user;

    request.get('/chat/friends').then(res => friends.value = res.data);
    request.get('/chat/friend-requests').then(res => friendRequests.value = res.data);

    window.addEventListener('resize', handleResize);
    initWebSocket();
});

onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize);
    if (typingTimeout.value) clearTimeout(typingTimeout.value);
});

onUnmounted(() => {
    if (ws) {
        ws.close(1000, '用户离开页面');
    }
    stopHeartbeat();
});

</script>

<style scoped>
/* 暗色主题变量 - 固定为暗色模式 */
.theme-dark {
    --bg-primary: #0f172a;
    --bg-secondary: #1e293b;
    --bg-tertiary: #334155;
    --bg-hover: #334155;
    --primary-color: #6366f1;
    --primary-hover: #818cf8;
    --border-color: #334155;
    --text-primary: #f8fafc;
    --text-secondary: #e2e8f0;
    --text-tertiary: #94a3b8;
    --success-color: #10b981;
    --danger-color: #ef4444;
    --nav-active-bg: rgba(99, 102, 241, 0.2);
    --card-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.3);
}

/* 主容器 */
.chat-container {
    display: flex;
    height: 100vh;
    /* 直接占满视口高度，不再依赖固定减值 */
    width: 100%;
    overflow: hidden;
    background-color: var(--bg-primary);
    color: var(--text-primary);
}

/* 侧边栏 */
.chat-sidebar {
    width: 360px;
    background: var(--bg-secondary);
    border-right: 1px solid var(--border-color);
    display: flex;
    flex-direction: column;
    overflow: hidden;
    transition: width 0.3s ease;
}

.sidebar-header {
    padding: 1rem;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    gap: 0.5rem;
}

.search-box {
    flex: 1;
    position: relative;
}

.search-box input {
    width: 100%;
    padding: 0.6rem 0.6rem 0.6rem 2rem;
    background: var(--bg-primary);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    color: var(--text-primary);
    font-size: 0.9rem;
    transition: all 0.3s ease;
}

.search-box input:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.1);
}

.search-box i {
    position: absolute;
    left: 0.7rem;
    top: 50%;
    transform: translateY(-50%);
    color: var(--text-tertiary);
}

.add-friend-btn {
    width: 40px;
    height: 40px;
    border-radius: 8px;
    background: var(--primary-color);
    color: white;
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
}

.add-friend-btn:hover {
    background: var(--primary-hover);
    transform: rotate(90deg);
}

/* 好友请求通知 */
.friend-requests-notification {
    padding: 0.8rem 1.2rem;
    background-color: rgba(99, 102, 241, 0.1);
    border-bottom: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    gap: 0.8rem;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.friend-requests-notification:hover {
    background-color: rgba(99, 102, 241, 0.2);
}

.friend-requests-notification i {
    color: var(--primary-color);
    font-size: 1.1rem;
}

.friend-requests-notification span {
    flex: 1;
    color: var(--text-secondary);
    font-size: 0.9rem;
}

.notification-badge {
    background: var(--primary-color);
    color: white;
    font-size: 0.8rem;
    min-width: 20px;
    height: 20px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 0.3rem;
}

/* 好友列表 */
.friends-list {
    flex: 1;
    overflow-y: auto;
    padding: 0.5rem 0;
}

.friends-list::-webkit-scrollbar {
    width: 6px;
}

.friends-list::-webkit-scrollbar-track {
    background: var(--bg-secondary);
}

.friends-list::-webkit-scrollbar-thumb {
    background: var(--border-color);
    border-radius: 3px;
}

.friends-list::-webkit-scrollbar-thumb:hover {
    background: var(--text-tertiary);
}

.list-section {
    margin-bottom: 1.5rem;
}

.section-title {
    padding: 0 1.2rem 0.5rem;
    color: var(--text-tertiary);
    font-size: 0.8rem;
    text-transform: uppercase;
    letter-spacing: 1px;
}

.friend-item {
    padding: 0.8rem 1.2rem;
    display: flex;
    align-items: center;
    gap: 1rem;
    cursor: pointer;
    transition: background 0.3s ease;
}

.friend-item:hover {
    background: var(--bg-hover);
}

.friend-item.active {
    background: var(--nav-active-bg);
}

.friend-avatar {
    position: relative;
    width: 48px;
    height: 48px;
    flex-shrink: 0;
}

.friend-avatar img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    object-fit: cover;
    border: 2px solid transparent;
    transition: all 0.3s ease;
}

.friend-item.active .friend-avatar img {
    border-color: var(--primary-color);
}

.online-indicator,
.offline-indicator {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 14px;
    height: 14px;
    border-radius: 50%;
    border: 2px solid var(--bg-secondary);
}

.online-indicator {
    background-color: var(--success-color);
    /* 绿色表示在线 */
}

.offline-indicator {
    background-color: var(--text-tertiary);
    /* 灰色表示离线 */
}

.friend-info {
    flex: 1;
    min-width: 0;
}

.friend-name {
    color: var(--text-primary);
    font-weight: 500;
    margin-bottom: 2px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.last-message {
    color: var(--text-tertiary);
    font-size: 0.85rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.last-message.unread {
    color: var(--primary-color);
    font-weight: 500;
}

.friend-meta {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 0.3rem;
}

.message-time {
    color: var(--text-tertiary);
    font-size: 0.75rem;
}

.unread-badge {
    background: var(--primary-color);
    color: white;
    font-size: 0.7rem;
    width: 18px;
    height: 18px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
}

/* 主聊天区域 */
.chat-main {
    flex: 1;
    display: flex;
    flex-direction: column;
    background-color: var(--bg-primary);
    overflow: hidden;
}

.chat-header {
    padding: 0.8rem 1.5rem;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: var(--bg-secondary);
}

.chat-header .friend-info {
    display: flex;
    align-items: center;
    gap: 1rem;
    cursor: pointer;
}

.chat-header .friend-name {
    font-size: 1.1rem;
    margin-bottom: 0;
}

.friend-status {
    color: var(--text-tertiary);
    font-size: 0.85rem;
}

.chat-actions {
    display: flex;
    gap: 0.5rem;
}

.action-btn {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    background: transparent;
    border: none;
    color: var(--text-secondary);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
}

.action-btn:hover {
    background: var(--bg-hover);
    color: var(--primary-color);
}

/* 聊天消息区域 */
.chat-messages {
    flex: 1;
    padding: 1.5rem;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 1rem;
    background-color: #0f172a;
    background-image:
        radial-gradient(circle at 10px 10px, rgba(99, 102, 241, 0.05) 1px, transparent 0);
    background-size: 30px 30px;
}

.chat-messages::-webkit-scrollbar {
    width: 8px;
}

.chat-messages::-webkit-scrollbar-track {
    background: var(--bg-primary);
}

.chat-messages::-webkit-scrollbar-thumb {
    background: var(--border-color);
    border-radius: 4px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
    background: var(--text-tertiary);
}

.date-divider {
    align-self: center;
    background: var(--bg-secondary);
    color: var(--text-tertiary);
    font-size: 0.75rem;
    padding: 0.3rem 0.8rem;
    border-radius: 12px;
    margin: 0.5rem 0;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.message {
    display: flex;
    max-width: 80%;
    animation: fadeIn 0.3s ease;
}

.message.sent {
    align-self: flex-end;
    flex-direction: row-reverse;
}

.message.received {
    align-self: flex-start;
}

.message-bubble {
    padding: 0.8rem 1rem;
    border-radius: 18px;
    position: relative;
    word-wrap: break-word;
    line-height: 1.5;
    max-width: calc(100% - 40px);
}

.message.sent .message-bubble {
    background: var(--primary-color);
    color: white;
    border-bottom-right-radius: 4px;
    box-shadow: 0 2px 4px rgba(99, 102, 241, 0.2);
}

.message.received .message-bubble {
    background: var(--bg-secondary);
    color: var(--text-primary);
    border-bottom-left-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message-time {
    margin-top: 0.3rem;
    font-size: 0.7rem;
    color: var(--text-tertiary);
    display: flex;
    align-items: center;
    gap: 0.2rem;
}

.message.sent .message-time {
    justify-content: flex-end;
}

/* 正在输入提示 */
.typing-indicator {
    align-self: flex-start;
    background: var(--bg-secondary);
    padding: 0.6rem 1rem;
    border-radius: 18px;
    display: flex;
    gap: 0.3rem;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.dot {
    width: 8px;
    height: 8px;
    background: var(--text-tertiary);
    border-radius: 50%;
    animation: typing 1.4s infinite ease-in-out both;
}

.dot:nth-child(1) {
    animation-delay: -0.32s;
}

.dot:nth-child(2) {
    animation-delay: -0.16s;
}

/* 消息输入区域 */
.message-input-area {
    padding: 1rem;
    border-top: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    gap: 0.8rem;
    background-color: var(--bg-secondary);
}

.input-tools {
    display: flex;
    gap: 0.5rem;
}

.tool-btn {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    background: transparent;
    border: none;
    color: var(--text-secondary);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
}

.tool-btn:hover {
    background: var(--bg-hover);
    color: var(--primary-color);
}

.message-input {
    flex: 1;
    padding: 0.8rem 1rem;
    border-radius: 24px;
    background: var(--bg-primary);
    border: 1px solid var(--border-color);
    color: var(--text-primary);
    font-size: 0.95rem;
    resize: none;
    transition: all 0.3s ease;
    min-height: 48px;
    max-height: 120px;
    overflow-y: auto;
}

.message-input:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.1);
}

.message-input::placeholder {
    color: var(--text-tertiary);
}

.send-btn {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    background: var(--primary-color);
    color: white;
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    flex-shrink: 0;
}

.send-btn:hover {
    background: var(--primary-hover);
    transform: scale(1.05);
}

.send-btn:disabled {
    background: var(--border-color);
    cursor: not-allowed;
    transform: none;
}

/* 未选择好友时的提示 */
.no-selection {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    background: var(--bg-primary);
    color: var(--text-tertiary);
}

.no-selection-content {
    text-align: center;
    padding: 2rem;
}

.no-selection-content i {
    font-size: 3rem;
    margin-bottom: 1rem;
    color: var(--border-color);
    opacity: 0.5;
}

.no-selection-content h3 {
    font-size: 1.2rem;
    margin-bottom: 0.5rem;
    color: var(--text-primary);
}

/* 好友资料卡片 */
.profile-card {
    position: absolute;
    width: 350px;
    background: var(--bg-secondary);
    border-radius: 12px;
    box-shadow: var(--card-shadow);
    border: 1px solid var(--border-color);
    z-index: 1000;
    overflow: hidden;
    animation: scaleIn 0.3s ease;
}

.profile-header {
    padding: 1.5rem;
    background: linear-gradient(135deg, var(--primary-color), #8b5cf6);
    color: white;
    display: flex;
    align-items: center;
    gap: 1rem;
    position: relative;
}

.profile-avatar {
    width: 70px;
    height: 70px;
    border-radius: 50%;
    object-fit: cover;
    border: 3px solid rgba(255, 255, 255, 0.3);
}

.profile-name-status {
    flex: 1;
}

.profile-name {
    font-size: 1.2rem;
    font-weight: bold;
    margin-bottom: 0.3rem;
}

.profile-status {
    display: flex;
    align-items: center;
    gap: 6px;
    /* 状态点和文字间距 */
}

.status-dot {
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    /* 圆形状态点 */
}

/* 在线（绿色） */
.status-dot.online {
    background-color: #4cd964;
}

/* 忙碌（红色） */
.status-dot.busy {
    background-color: #ff3b30;
}

/* 离开（黄色） */
.status-dot.away {
    background-color: #ffcc00;
}

/* 离线（灰色） */
.status-dot.offline {
    background-color: #8e8e93;
}

.close-profile {
    position: absolute;
    top: 0.8rem;
    right: 0.8rem;
    background: transparent;
    border: none;
    color: rgba(255, 255, 255, 0.8);
    cursor: pointer;
    font-size: 1rem;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
}

.close-profile:hover {
    background: rgba(255, 255, 255, 0.2);
    color: white;
}

.profile-body {
    padding: 1.2rem 1.5rem;
}

.profile-info-item {
    display: flex;
    margin-bottom: 1rem;
    padding-bottom: 1rem;
    border-bottom: 1px solid var(--border-color);
}

.profile-info-item:last-child {
    margin-bottom: 0;
    padding-bottom: 0;
    border-bottom: none;
}

.profile-info-item label {
    width: 80px;
    color: var(--text-tertiary);
    font-size: 0.9rem;
}

.profile-info-item span {
    flex: 1;
    color: var(--text-primary);
    font-size: 0.95rem;
    word-break: break-word;
}

.profile-actions {
    display: flex;
    padding: 1rem 1.5rem;
    border-top: 1px solid var(--border-color);
    gap: 0.8rem;
}

.message-btn {
    flex: 1;
    padding: 0.7rem;
    background: var(--primary-color);
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-size: 0.9rem;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
}

.message-btn:hover {
    background: var(--primary-hover);
}

.more-btn {
    width: 40px;
    height: 40px;
    border-radius: 8px;
    background: var(--bg-tertiary);
    color: var(--text-secondary);
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
}

.more-btn:hover {
    background: var(--bg-hover);
    color: var(--text-primary);
}

.profile-backdrop {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 999;
    backdrop-filter: blur(2px);
    animation: fadeIn 0.2s ease;
}

/* 添加好友弹窗 */
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    backdrop-filter: blur(4px);
    animation: fadeIn 0.3s ease;
}

.modal {
    background: var(--bg-secondary);
    border-radius: 12px;
    width: 90%;
    max-width: 400px;
    box-shadow: var(--card-shadow);
    border: 1px solid var(--border-color);
    animation: scaleIn 0.3s ease;
}

.modal-header {
    padding: 1.2rem 1.5rem;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.modal-header h3 {
    margin: 0;
    font-size: 1.1rem;
    color: var(--text-primary);
}

.close-btn {
    background: transparent;
    border: none;
    color: var(--text-tertiary);
    cursor: pointer;
    font-size: 1.2rem;
    transition: color 0.3s ease;
}

.close-btn:hover {
    color: var(--text-primary);
}

.modal-body {
    padding: 1.5rem;
}

.search-input {
    width: 100%;
    padding: 0.8rem 1rem;
    background: var(--bg-primary);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    color: var(--text-primary);
    font-size: 0.95rem;
    margin-bottom: 1rem;
    transition: all 0.3s ease;
}

.search-input:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.1);
}

.search-btn {
    width: 100%;
    padding: 0.8rem;
    background: var(--primary-color);
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-size: 0.95rem;
    transition: background 0.3s ease;
}

.search-btn:hover {
    background: var(--primary-hover);
}

.search-btn:disabled {
    background: var(--border-color);
    cursor: not-allowed;
}

.search-results {
    margin-top: 1.5rem;
}

.search-results h4 {
    margin-bottom: 1rem;
    color: var(--text-tertiary);
    font-size: 0.9rem;
}

.user-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0.8rem 0;
    border-bottom: 1px solid var(--border-color);
}

.user-item:last-child {
    border-bottom: none;
}

.user-avatar {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    object-fit: cover;
}

.user-info {
    margin-left: 1rem;
    flex: 1;
}

.user-name {
    color: var(--text-primary);
    font-weight: 500;
}

.user-username {
    color: var(--text-tertiary);
    font-size: 0.8rem;
}

.user-signature {
    color: var(--text-tertiary);
    font-size: 0.8rem;
    margin-top: 0.2rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.add-btn {
    padding: 0.4rem 1rem;
    border-radius: 6px;
    background: var(--primary-color);
    color: white;
    border: none;
    cursor: pointer;
    font-size: 0.85rem;
    transition: all 0.3s ease;
}

.add-btn:hover {
    background: var(--primary-hover);
}

.add-btn:disabled {
    background: var(--border-color);
    cursor: not-allowed;
}

/* 好友请求弹窗样式 */
.request-item {
    display: flex;
    align-items: center;
    padding: 1rem 0;
    border-bottom: 1px solid var(--border-color);
}

.request-item:last-child {
    border-bottom: none;
}

.request-avatar {
    width: 54px;
    height: 54px;
    border-radius: 50%;
    object-fit: cover;
}

.request-info {
    margin-left: 1rem;
    flex: 1;
}

.request-name {
    color: var(--text-primary);
    font-weight: 500;
    font-size: 1rem;
}

.request-username {
    color: var(--text-tertiary);
    font-size: 0.85rem;
    margin-bottom: 0.3rem;
}

.request-time {
    color: var(--text-tertiary);
    font-size: 0.8rem;
}

.request-actions {
    display: flex;
    gap: 0.5rem;
}

.accept-btn,
.reject-btn {
    padding: 0.5rem 1rem;
    border-radius: 6px;
    border: none;
    cursor: pointer;
    font-size: 0.85rem;
    display: flex;
    align-items: center;
    gap: 0.3rem;
    transition: all 0.3s ease;
}

.accept-btn {
    background: var(--success-color);
    color: white;
}

.accept-btn:hover {
    background: #059669;
}

.reject-btn {
    background: var(--danger-color);
    color: white;
}

.reject-btn:hover {
    background: #dc2626;
}

.no-requests {
    text-align: center;
    padding: 2rem 0;
    color: var(--text-tertiary);
    font-size: 0.95rem;
}

/* 动画 */
@keyframes fadeIn {
    from {
        opacity: 0;
    }

    to {
        opacity: 1;
    }
}

@keyframes scaleIn {
    from {
        transform: scale(0.95);
        opacity: 0;
    }

    to {
        transform: scale(1);
        opacity: 1;
    }
}

@keyframes typing {
    0% {
        transform: translateY(0);
    }

    28% {
        transform: translateY(-5px);
    }

    44% {
        transform: translateY(0);
    }
}

/* 响应式设计 */
@media (max-width: 768px) {
    .chat-sidebar {
        width: 100%;
        position: absolute;
        height: 100%;
        z-index: 100;
        transform: translateX(-100%);
    }

    .chat-sidebar.active {
        transform: translateX(0);
    }

    .chat-main {
        width: 100%;
    }

    .message {
        max-width: 90%;
    }

    .profile-card {
        width: 90%;
        max-width: 350px;
    }
}

@media (max-width: 480px) {
    .chat-messages {
        padding: 1rem 0.5rem;
    }

    .message-input-area {
        padding: 0.8rem 0.5rem;
    }

    .tool-btn {
        width: 32px;
        height: 32px;
    }

    .send-btn {
        width: 40px;
        height: 40px;
    }

    .friend-name,
    .friend-status {
        max-width: 120px;
    }
}

.back-btn {
    width: 44px;
    height: 38px;
    border-radius: 6px;
    background-color: #1e293b;
    border: 1px solid #6366f1;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    margin-right: 8px;
    padding: 0;
}

/* 重点优化箭头图标 */
.back-btn i.fa-arrow-left {
    color: #6366f1;
    /* 箭头使用主题色，更醒目 */
    font-size: 1.4rem;
    /* 增大箭头尺寸 */
    font-weight: 600;
    /* 加粗箭头 */
}

/* 悬停效果增强箭头识别度 */
.back-btn:hover {
    background-color: #6366f1;
}

.back-btn:hover i.fa-arrow-left {
    color: white;
    /* 悬停时箭头变白，形成强烈对比 */
    transform: translateX(-2px);
    /* 箭头轻微左移，增强"返回"的动势感 */
}

/* 弹窗底部按钮区域 */
.modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 0.5rem;
    padding: 1rem 1.5rem;
    border-top: 1px solid var(--border-color);
}

/* 取消按钮 */
.cancel-btn {
    padding: 0.6rem 1.2rem;
    border-radius: 8px;
    background: var(--bg-tertiary);
    color: var(--text-primary);
    border: none;
    cursor: pointer;
    font-size: 0.9rem;
    transition: background 0.3s ease;
}

.cancel-btn:hover {
    background: var(--bg-hover);
}

/* 确认按钮 */
.confirm-btn {
    padding: 0.6rem 1.2rem;
    border-radius: 8px;
    background: var(--primary-color);
    color: white;
    border: none;
    cursor: pointer;
    font-size: 0.9rem;
    transition: background 0.3s ease;
}

.confirm-btn:hover {
    background: var(--primary-hover);
}

/* 验证消息输入框 */
.verify-message-input {
    width: 100%;
    padding: 0.8rem;
    margin-bottom: 1rem;
    background: var(--bg-primary);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    color: var(--text-primary);
    font-size: 0.95rem;
    resize: none;
}
</style>
